from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton,
    QTextEdit, QGroupBox, QGridLayout, QCheckBox,QRadioButton, QTableView, QHeaderView, QComboBox
)
from PyQt6.QtCore import QAbstractTableModel
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont
import json
import os

# 导入ToggleSwitch组件
import sys
sys.path.append(os.path.dirname(__file__))
from communication import ToggleSwitch
from config_manager import config_manager

class GreetingTableModel(QAbstractTableModel):
    """打招呼记录表格模型"""
    
    def __init__(self, data=None):
        super().__init__()
        self._data = data or []
        self._headers = ["招呼职位顺序", "次数", "操作"]
    
    def rowCount(self, parent=None):
        return len(self._data)
    
    def columnCount(self, parent=None):
        return 3
    
    def data(self, index, role=Qt.ItemDataRole.DisplayRole):
        if role == Qt.ItemDataRole.DisplayRole:
            row_data = self._data[index.row()]
            if index.column() == 0:
                return row_data[0]
            elif index.column() == 1:
                return row_data[1]
            else:  # 操作列
                return "🗑️"
        return None
    
    def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole):
        if role == Qt.ItemDataRole.DisplayRole and orientation == Qt.Orientation.Horizontal:
            return self._headers[section]
        return None

class GreetingWidget(QWidget):
    def __init__(self):
        super().__init__()
        
        # 存储所有UI字段的引用
        self.ui_fields = {}
        # 配置文件名
        self.config_filename = "greeting_config.json"  # 改为更明确的名称
        
        # 迁移旧配置文件
        old_config_path = "a.json"
        config_manager.migrate_old_config(old_config_path, self.config_filename)
        
        # 默认配置数据
        self.default_config = {
            "tableName": "sh",
            "position": "",
            "location": "",
            "tags": "",
            "tableData": [
                {"name": i, "address": "10" if i <= 10 else "5"}
                for i in range(1, 112)
            ],
            "experience": "",
            "speedEnd2": "",
            "positionsw": False,
            "locationsw": False,
            "tagssw": False,
            "experiencesw": False,
            "greet": True,
            "limityx": False,
            "limitXl2": False,
            "priority": True,
            "exchangeContact": False,
            "replyNewMessage": True,
            "filterColleagues": False,
            "limitAge": False,
            "limitSex": False,
            "tuijian": {
                "recommend": True,
                "latest": False,
                "student": False
            },
            "limitXl": False,
            "filterPeople": False,
            "checkList": ["大专", "本科"],
            "checkList2": ["离职-找工作"],
            "checkList3": [],
            "ageStart": "10",
            "ageEnd": "43",
            "experienceStart": "",
            "experienceEnd": "",
            "salaryStart": "2千",
            "salaryEnd": "2万",
            "genderList": "",
            "activityLevel": ["今日活跃"],
            "limitExperience": True,
            "limitSalary": True,
            "settings": {
                "returnCommunication": True,
                "filterConditions": False,
                "increaseExposure": False,
                "superExposure": False,
                "freeTalentCommunication": False,
                "maxStayTime": "20分钟一次",
                "greetingFrequency": "0分钟一次",
                "response1": "",
                "response2": ""
            }
        }
        
        # 加载配置
        self.config_data = config_manager.load_config(self.config_filename, self.default_config)
        
        self.init_ui()
        self.load_config()
    
    def load_config(self):
        """从AppData加载配置数据到UI字段"""
        try:
            self.config_data = config_manager.load_config(self.config_filename, self.default_config)
            
            # 加载表格数据
            if 'tableData' in self.config_data:
                table_data = [[str(item['name']), str(item['address'])] for item in self.config_data['tableData']]
                self.ui_fields['greeting_table']._data = table_data
                self.ui_fields['greeting_table'].layoutChanged.emit()
            
            # 加载功能设置
            function_mapping = {
                'greet': 'greet',
                'priority': 'priority', 
                'exchangeContact': 'exchangeContact',
                'replyNewMessage': 'replyNewMessage',
                'filterColleagues': 'filterColleagues',
                'recommend': ('tuijian', 'recommend'),
                'latest': ('tuijian', 'latest'),
                'student': ('tuijian', 'student'),
                'filterConditions': ('settings', 'filterConditions'),
                'returnCommunication': ('settings', 'returnCommunication'),
                'freeTalentCommunication': ('settings', 'freeTalentCommunication'),
                'increaseExposure': ('settings', 'increaseExposure')
            }
            
            for field_name, config_path in function_mapping.items():
                if field_name in self.ui_fields:
                    if isinstance(config_path, tuple):
                        value = self.config_data.get(config_path[0], {}).get(config_path[1], False)
                    else:
                        value = self.config_data.get(config_path, False)
                    self.ui_fields[field_name].setChecked(value)
            
            # 加载其他设置
            if 'settings' in self.config_data:
                settings = self.config_data['settings']
                if 'greetingFrequency' in settings:
                    freq = settings['greetingFrequency'].replace('分钟一次', '')
                    if freq in ["0", "1", "2", "3", "4", "5", "10", "15", "20", "30", "40", "50"]:
                        self.ui_fields['greeting_frequency'].setCurrentText(freq)
                
                self.ui_fields['response1'].setPlainText(settings.get('response1', ''))
                self.ui_fields['response2'].setPlainText(settings.get('response2', ''))
            
            # 加载筛选条件
            if 'limitAge' in self.config_data:
                self.ui_fields['age_unlimited'].setChecked(not self.config_data['limitAge'])
            if 'ageStart' in self.config_data:
                self.ui_fields['age_start'].setText(self.config_data['ageStart'])
            if 'ageEnd' in self.config_data:
                self.ui_fields['age_end'].setText(self.config_data['ageEnd'])
            
            # 加载学历设置
            if 'checkList' in self.config_data:
                education_list = self.config_data['checkList']
                education_options = ["初中及以下", "中专/中技", "高中", "大专", "本科", "硕士", "博士"]
                for option in education_options:
                    field_name = f'education_{option}'
                    if field_name in self.ui_fields:
                        self.ui_fields[field_name].setChecked(option in education_list)
            
            print("配置加载成功")
            
        except Exception as e:
            print(f"加载配置失败: {e}")
    
    def save_config(self):
        """保存配置到AppData的JSON文件"""
        try:
            # 更新表格数据
            table_data = []
            for i, row in enumerate(self.ui_fields['greeting_table']._data):
                table_data.append({
                    "name": int(row[0]) if row[0].isdigit() else i+1,
                    "address": int(row[1]) if row[1].isdigit() else row[1]
                })
            
            # 更新配置数据
            self.config_data.update({
                "tableData": table_data,
                "greet": self.ui_fields['greet'].isChecked(),
                "priority": self.ui_fields['priority'].isChecked(),
                "exchangeContact": self.ui_fields['exchangeContact'].isChecked(),
                "replyNewMessage": self.ui_fields['replyNewMessage'].isChecked(),
                "filterColleagues": self.ui_fields['filterColleagues'].isChecked(),
                "tuijian": {
                    "recommend": self.ui_fields['recommend'].isChecked(),
                    "latest": self.ui_fields['latest'].isChecked(),
                    "student": self.ui_fields['student'].isChecked()
                },
                "limitAge": not self.ui_fields['age_unlimited'].isChecked(),
                "ageStart": self.ui_fields['age_start'].text(),
                "ageEnd": self.ui_fields['age_end'].text(),
                "settings": {
                    **self.config_data.get('settings', {}),
                    "returnCommunication": self.ui_fields['returnCommunication'].isChecked(),
                    "filterConditions": self.ui_fields['filterConditions'].isChecked(),
                    "increaseExposure": self.ui_fields['increaseExposure'].isChecked(),
                    "freeTalentCommunication": self.ui_fields['freeTalentCommunication'].isChecked(),
                    "greetingFrequency": f"{self.ui_fields['greeting_frequency'].currentText()}分钟一次",
                    "response1": self.ui_fields['response1'].toPlainText(),
                    "response2": self.ui_fields['response2'].toPlainText()
                }
            })
            
            # 保存到AppData
            config_manager.save_config(self.config_filename, self.config_data)
            print(f"配置已保存到: {config_manager.get_config_path(self.config_filename)}")
            
            # 打印完整的JSON配置
            print("=== 问候配置JSON ===")
            print(json.dumps(self.config_data, ensure_ascii=False, indent=2))
            print("===================")
            
            return self.config_data
            
        except Exception as e:
            print(f"保存配置失败: {e}")
            return None
    
    def init_ui(self):
        """初始化打招呼界面 - 左右布局"""
        self.setStyleSheet("""
            QWidget {
                background-color: white;
                color: black;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
            }
            QLabel {
                color: black;
                font-size: 11px;
                border: none;
            }
            QLineEdit {
                background-color: white;
                color: black;
                border: 1px solid #d0d7de;
                border-radius: 6px;
                padding: 6px 8px;
                font-size: 13px;
            }
            QLineEdit:focus {
                border-color: #0969da;
                box-shadow: 0 0 0 3px rgba(9, 105, 218, 0.3);
            }
            QTextEdit {
                background-color: white;
                color: black;
                border: 1px solid #d0d7de;
                border-radius: 6px;
                padding: 8px;
                font-size: 13px;
            }
            QTextEdit:focus {
                border-color: #0969da;
            }
            QPushButton {
                background-color: #0969da;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 8px 16px;
                font-size: 13px;
                font-weight: 500;
            }
            QPushButton:hover {
                background-color: #0860ca;
            }
            QPushButton:pressed {
                background-color: #0757ba;
            }
            QCheckBox {
                color: black;
                font-size: 13px;
                spacing: 8px;
            }
            QCheckBox::indicator {
                width: 16px;
                height: 16px;
                border-radius: 3px;
                border: 1px solid #d0d7de;
                background-color: white;
            }
        """)
        
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(10)
        
        # 通用样式定义
        self.input_style = """
            QLineEdit {
                background-color: white;
                color: black;
                border: 1px solid #ccc;
                padding: 4px;
                border-radius: 3px;
            }
        """
        self.label_style = """
           QLabel {
                font-size: 11px;
                color: black;
                background-color: white;
                border: none;
            }
        """
        
        self.button_style = """
            QPushButton {
                background-color: #007bff;
                color: white;
                border: none;
                padding: 6px 12px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
        """
        
        # 标题和保存按钮
        header_layout = QHBoxLayout()
        
        title_label = QLabel("👋 问候配置管理")
        title_label.setStyleSheet("""
            QLabel {
                font-size: 20px;
                font-weight: bold;
                color: black;
                background-color: white;
                border: none;
            }
        """)
        header_layout.addWidget(title_label)
        
        header_layout.addStretch()
        
        # 保存按钮
        save_btn = QPushButton("💾 保存配置")
        save_btn.setStyleSheet("""
            QPushButton {
                background-color: #007bff;
                color: white;
                border: none;
                padding: 8px 20px;
                border-radius: 4px;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
            QPushButton:pressed {
                background-color: #004085;
            }
        """)
        # 连接保存按钮的点击事件
        save_btn.clicked.connect(self.save_config)
        header_layout.addWidget(save_btn)
        
        main_layout.addLayout(header_layout)
        
        # 直接使用主布局，不用滚动区域
        content_layout = QHBoxLayout()
        content_layout.setSpacing(15)

        # 左侧配置区域 (2/5 比例)
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        left_layout.setContentsMargins(0, 0, 0, 0)
        self.create_greeting_records(left_layout)
        content_layout.addWidget(left_widget, 3)  # 2/5 比例

        # 右侧配置区域 (3/5 比例)
        right_widget = QWidget()
        right_layout = QVBoxLayout(right_widget)
        right_layout.setContentsMargins(0, 0, 0, 0)
        self.create_function_settings(right_layout)
        self.create_filter_conditions(right_layout)
        self.create_other_settings(right_layout)
        content_layout.addWidget(right_widget, 5)  # 3/5 比例

        # 直接添加到主布局，不用滚动区域
        main_layout.addLayout(content_layout)
    
    def create_greeting_records(self, parent_layout):
        """创建招呼记录分组"""
        group = QGroupBox("📝 招呼记录")
        group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                color: black;
                background-color: white;
                border: 1px solid #ccc;
                border-radius: 6px;
                margin-top: 8px;
                padding-top: 8px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
                color: black;
            }
        """)
        layout = QVBoxLayout(group)
        layout.setSpacing(8)
        
        # 顶部输入区域
        input_layout = QHBoxLayout()
        input_layout.setSpacing(8)
        
        sequence_input = QLabel("第")
        sequence_input.setStyleSheet(self.label_style)
        input_layout.addWidget(sequence_input)
        
        desc_input = QLineEdit()
        desc_input.setPlaceholderText("")
        desc_input.setStyleSheet(self.input_style)
        self.ui_fields['position_input'] = desc_input
        input_layout.addWidget(desc_input)
        
        sequence_input2 = QLabel("个职位打招呼")
        sequence_input2.setStyleSheet(self.label_style)
        input_layout.addWidget(sequence_input2)
        
        times_input = QLineEdit()
        times_input.setPlaceholderText("")
        times_input.setStyleSheet(self.input_style)
        self.ui_fields['times_input'] = times_input
        input_layout.addWidget(times_input)
        
        sequence_input3 = QLabel("次")
        sequence_input3.setStyleSheet(self.label_style)
        input_layout.addWidget(sequence_input3)
        
        add_btn = QPushButton("导入")
        add_btn.setFixedWidth(60)
        add_btn.setStyleSheet(self.button_style)
        input_layout.addWidget(add_btn)
        
        layout.addLayout(input_layout)
        
        # 表格区域
        table_view = QTableView()
        table_view.setMaximumHeight(280)
        table_view.setStyleSheet("""
           QTableView {
                background-color: white;
                color: black;
                border: none;
                gridline-color: #dee2e6;
                border-radius: 0px;
                selection-background-color: #e7f3ff;
                selection-color: black;
            }
            QTableView::item {
                padding: 6px;
                color: black;
                background-color: white;
            }
            QTableView::item:selected {
                color: black;
                border: none;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                color: black;
                padding: 6px;
                font-weight: bold;
                font-size: 12px;
            }
        """)
        
        table_model = GreetingTableModel()
        table_view.setModel(table_model)
        self.ui_fields['greeting_table'] = table_model
        
        header = table_view.horizontalHeader()
        if header:
            header.setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
            header.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
            header.setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed)
        table_view.setColumnWidth(2, 60)
        
        # 移除表格边距和间距
        table_view.setContentsMargins(0, 0, 0, 0)
        if table_view.verticalHeader():
            table_view.verticalHeader().setVisible(False)  # 隐藏行号
        
        layout.addWidget(table_view)
        
        # 时间设置
        time_layout = QHBoxLayout()
        time_layout.setSpacing(8)
        
        a = QLabel("打招呼频率: ")
        a.setStyleSheet(self.label_style)
        a.setFixedWidth(80)
        time_layout.addWidget(a)
        
        time_input2 = QComboBox()
        time_input2.addItems(["0", "1", "2", "3", "4", "5", "10", "15", "20", "30", "40", "50"])
        time_input2.setStyleSheet(self.input_style)
        self.ui_fields['greeting_frequency'] = time_input2
        time_layout.addWidget(time_input2)
        
        b = QLabel("分钟一次")
        b.setFixedWidth(80)
        b.setStyleSheet(self.label_style)
        time_layout.addWidget(b)
        
        layout.addLayout(time_layout)
        
        # 回复内容区域
        reply_layout = QVBoxLayout()
        reply_layout.setSpacing(6)
        
        c = QLabel("(1) 回复内容: ")
        c.setStyleSheet(self.label_style)
        c.setFixedWidth(80)
        c.setFixedHeight(20)
        reply_layout.addWidget(c)
        
        reply_input1 = QTextEdit()
        reply_input1.setMaximumHeight(50)
        reply_input1.setStyleSheet("""
            QTextEdit {
                background-color: white;
                color: black;
                border: 1px solid #ccc;
                padding: 4px;
            }
        """)
        reply_input1.setFixedHeight(50)
        self.ui_fields['response1'] = reply_input1
        reply_layout.addWidget(reply_input1)
        
        d = QLabel("(2) 回复内容: ")
        d.setStyleSheet(self.label_style)
        d.setFixedWidth(80)
        d.setFixedHeight(20)
        reply_layout.addWidget(d)
        
        reply_input2 = QTextEdit()
        reply_input2.setMaximumHeight(50)
        reply_input2.setStyleSheet("""
            QTextEdit {
                background-color: white;
                color: black;
                border: 1px solid #ccc;
                padding: 4px;
            }
        """)
        reply_input2.setFixedHeight(50)
        self.ui_fields['response2'] = reply_input2
        reply_layout.addWidget(reply_input2)
        
        layout.addLayout(reply_layout)
        parent_layout.addWidget(group)
    
    def add_greeting_record(self):
        """添加招呼记录"""
        position = self.desc_input.text().strip()
        count = self.times_input.text().strip()
        
        if position and count:
            # 添加到配置数据
            self.config_data["tableData"].append({
                "name": int(position),
                "address": count
            })
            
            # 更新表格
            table_data = [(str(record["name"]), record["address"]) for record in self.config_data["tableData"]]
            self.table_model._data = table_data
            self.table_model.layoutChanged.emit()
            
            # 清空输入框
            self.desc_input.clear()
            self.times_input.clear()
    
    def create_function_settings(self, parent_layout):
        """创建功能设置分组"""
        group = QGroupBox("⚙️ 功能设置")
        group.setFixedHeight(130)
        group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                color: black;
                background-color: white;
                border: 1px solid #ccc;
                border-radius: 6px;
                margin-top: 8px;
                padding-top: 8px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
                color: black;
            }
        """)
        layout = QVBoxLayout(group)
        layout.setSpacing(8)
        
        # 功能开关 - 使用网格布局
        switches_layout = QGridLayout()
        switches_layout.setSpacing(5)
        switches_layout.setVerticalSpacing(2)
        
        function_switches = [
            ("打招呼", "greet", True), ("优先执行", "priority", True), ("交换微信/手机", "exchangeContact", False),
            ("回复新消息", "replyNewMessage", True), ("过滤同事已聊", "filterColleagues", False), ("推荐牛人", "recommend", True),
            ("最新", "latest", True), ("学生", "student", False), ("不耗权益筛选条件", "filterConditions", True),
            ("权益用完返回沟通", "returnCommunication", True), ("权益用完沟通免费人才", "freeTalentCommunication", False), ("不耗权益增加曝光", "increaseExposure", False)
        ]
        
        for i, (text, field_name, checked) in enumerate(function_switches):
            switch_layout = QHBoxLayout()
            switch_layout.setSpacing(2)
            switch_layout.setContentsMargins(0, 0, 0, 0)
            
            label = QLabel(text)
            label.setFixedHeight(18)
            label.setStyleSheet("color: black; font-size: 11px; border: none;")
            
            switch = ToggleSwitch(text, checked)
            switch.setFixedHeight(18)
            self.ui_fields[field_name] = switch
            
            switch_layout.addWidget(label)
            switch_layout.addWidget(switch)
            switch_layout.addStretch()
            
            row = i // 3
            col = i % 3
            switches_layout.addLayout(switch_layout, row, col)
        
        layout.addLayout(switches_layout)
        parent_layout.addWidget(group)
    
    def create_filter_conditions(self, parent_layout):
        """创建筛选条件分组"""
        group = QGroupBox("🔍 筛选条件")
        group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                color: black;
                background-color: white;
                border: 1px solid #ccc;
                border-radius: 6px;
                margin-top: 8px;
                padding-top: 8px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
                color: black;
            }
        """)
        layout = QVBoxLayout(group)
        layout.setSpacing(8)
        
        # 经验不限
        exp_layout = QHBoxLayout()
        exp_layout.addWidget(QLabel("经验不限"))
        
        self.exp_switch = ToggleSwitch("经验不限", self.config_data["limitExperience"])
        self.exp_switch.setFixedHeight(18)
        exp_layout.addWidget(self.exp_switch)
 
        
        self.exp_input1 = QLineEdit(self.config_data["experienceStart"])
        self.exp_input1.setFixedWidth(40)
        self.exp_input1.setStyleSheet(self.input_style)
        exp_layout.addWidget(self.exp_input1)
        
        exp_layout.addWidget(QLabel("--"))
        
        self.exp_input2 = QLineEdit(self.config_data["experienceEnd"])
        self.exp_input2.setFixedWidth(40)
        self.exp_input2.setStyleSheet(self.input_style)
        exp_layout.addWidget(self.exp_input2)
        
        exp_layout.addWidget(QLabel("年"))
        exp_layout.addStretch()
        layout.addLayout(exp_layout)
        
        # 期望月薪
        salary_layout = QHBoxLayout()
        salary_layout.addWidget(QLabel("期望月薪"))
        
        self.salary_switch = ToggleSwitch("期望月薪", self.config_data["limitSalary"])
        self.salary_switch.setFixedHeight(18)
        salary_layout.addWidget(self.salary_switch)


        salary_layout.addWidget(QLabel("薪资范围"))
        
        self.salary_combo1 = QComboBox()
        self.salary_combo1.addItems(["2千", "3千", "4千", "5千", "6千", "8千", "10千", "15千", "20千"])
        self.salary_combo1.setCurrentText(self.config_data["salaryStart"])
        salary_layout.addWidget(self.salary_combo1)
        
        salary_layout.addWidget(QLabel("--"))
        
        self.salary_combo2 = QComboBox()
        self.salary_combo2.addItems(["5万", "10万", "15万", "20万", "25万", "30万", "40万", "50万"])
        self.salary_combo2.setCurrentText(self.config_data["salaryEnd"])
        salary_layout.addWidget(self.salary_combo2)
        
        salary_layout.addStretch()  # 添加弹性空间，使控件左对齐
        layout.addLayout(salary_layout)
        
        # 性别不限
        gender_layout = QHBoxLayout()
        gender_layout.addWidget(QLabel("性别不限"))
        
        self.gender_switch = ToggleSwitch("性别不限", self.config_data["limitSex"])
        self.gender_switch.setFixedHeight(18)
        gender_layout.addWidget(self.gender_switch)
        
        self.male_radio = QRadioButton("男")
        self.female_radio = QRadioButton("女")
        if self.config_data["genderList"] == "男":
            self.male_radio.setChecked(True)
        else:
            self.female_radio.setChecked(True)
        gender_layout.addWidget(self.male_radio)
        gender_layout.addWidget(self.female_radio)
        gender_layout.addStretch()  # 添加弹性空间，使控件左对齐
        layout.addLayout(gender_layout)
        
        # 年龄不限
        age_layout = QHBoxLayout()
        age_layout.addWidget(QLabel("年龄不限"))
        
        self.age_switch = ToggleSwitch("年龄不限", self.config_data["limitAge"])
        self.age_switch.setFixedHeight(18)
        age_layout.addWidget(self.age_switch)
        # 添加到ui_fields字典
        self.ui_fields['age_unlimited'] = self.age_switch
        
        self.age_input1 = QLineEdit(self.config_data["ageStart"])
        self.age_input1.setFixedWidth(40)
        self.age_input1.setStyleSheet(self.input_style)
        age_layout.addWidget(self.age_input1)
        # 添加到ui_fields字典
        self.ui_fields['age_start'] = self.age_input1
        
        age_layout.addWidget(QLabel("--"))
        self.age_input2 = QLineEdit(self.config_data["ageEnd"])
        self.age_input2.setFixedWidth(40)
        self.age_input2.setStyleSheet(self.input_style)
        age_layout.addWidget(self.age_input2)
        # 添加到ui_fields字典
        self.ui_fields['age_end'] = self.age_input2
        
        age_layout.addWidget(QLabel("岁"))
        age_layout.addStretch()
        layout.addLayout(age_layout)
        
        # 活跃度
        activity_layout = QHBoxLayout()
        activity_layout.addWidget(QLabel("活跃度"))
        
        activity_options = ["今日活跃", "3天内活跃", "7天内活跃", "30天内活跃"]
        self.activity_checkboxes = {}
        for option in activity_options:
            cb = QCheckBox(option)
            if option in self.config_data["activityLevel"]:
                cb.setChecked(True)
            cb.setStyleSheet("color: black; font-size: 11px;")
            self.activity_checkboxes[option] = cb
            activity_layout.addWidget(cb)
        
        layout.addLayout(activity_layout)
        
        # 学历不限
        education_layout = QHBoxLayout()
        education_layout.addWidget(QLabel("学历不限"))
        
        self.education_switch = ToggleSwitch("学历不限", self.config_data["limitXl"])
        self.education_switch.setFixedHeight(18)
        education_layout.addWidget(self.education_switch)
        
        education_options = ["初中及以下", "中专/中技", "高中", "大专", "本科", "硕士", "博士"]
        self.education_checkboxes = {}
        for option in education_options:
            cb = QCheckBox(option)
            if option in self.config_data["checkList"]:
                cb.setChecked(True)
            cb.setStyleSheet("color: black; font-size: 11px;")
            self.education_checkboxes[option] = cb
            education_layout.addWidget(cb)
        
        education_layout.addStretch()  # 添加弹性空间，使控件左对齐
        layout.addLayout(education_layout)
        
        # 意向不限
        intention_layout = QHBoxLayout()
        intention_layout.addWidget(QLabel("意向不限"))
        
        self.intention_switch = ToggleSwitch("意向不限", self.config_data["limityx"])
        self.intention_switch.setFixedHeight(18)
        intention_layout.addWidget(self.intention_switch)
        
        intention_options = ["在职-找工作", "离职-找工作", "在职-不找工作", "在职-看机会"]
        self.intention_checkboxes = {}
        for option in intention_options:
            cb = QCheckBox(option)
            if option in self.config_data["checkList2"]:
                cb.setChecked(True)
            cb.setStyleSheet("color: black; font-size: 11px;")
            self.intention_checkboxes[option] = cb
            intention_layout.addWidget(cb)
        
        intention_layout.addStretch()  # 添加弹性空间，使控件左对齐
        layout.addLayout(intention_layout)
        
        # 学历不限 (第二行)
        school_layout = QHBoxLayout()
        school_layout.addWidget(QLabel("学历不限"))
        
        self.school_switch = ToggleSwitch("学历不限", self.config_data["limitXl2"])
        self.school_switch.setFixedHeight(18)
        school_layout.addWidget(self.school_switch)

        self.school_checkboxes = {}
        school_options = ["统招", "985", "211"]
        for option in school_options:
            cb = QCheckBox(option)
            if option in self.config_data["checkList3"]:
                cb.setChecked(True)
            cb.setStyleSheet("color: black; font-size: 11px;")
            self.school_checkboxes[option] = cb
            school_layout.addWidget(cb)

        
        
        school_layout.addStretch()
        layout.addLayout(school_layout)
        
        parent_layout.addWidget(group)
        
        # 添加所有UI字段到ui_fields字典
        self.ui_fields['exp_switch'] = self.exp_switch
        self.ui_fields['exp_input1'] = self.exp_input1
        self.ui_fields['exp_input2'] = self.exp_input2
        self.ui_fields['salary_switch'] = self.salary_switch
        self.ui_fields['salary_combo1'] = self.salary_combo1
        self.ui_fields['salary_combo2'] = self.salary_combo2
        self.ui_fields['gender_switch'] = self.gender_switch
        self.ui_fields['male_radio'] = self.male_radio
        self.ui_fields['female_radio'] = self.female_radio
        self.ui_fields['education_switch'] = self.education_switch
        self.ui_fields['intention_switch'] = self.intention_switch
        self.ui_fields['school_switch'] = self.school_switch
        
        # 添加复选框组
        for option, cb in self.activity_checkboxes.items():
            self.ui_fields[f'activity_{option}'] = cb
        
        for option, cb in self.education_checkboxes.items():
            self.ui_fields[f'education_{option}'] = cb
            
        for option, cb in self.intention_checkboxes.items():
            self.ui_fields[f'intention_{option}'] = cb
            
        for option, cb in self.school_checkboxes.items():
            self.ui_fields[f'school_{option}'] = cb
    
    def create_other_settings(self, parent_layout):
        """创建其他设置分组"""
        group = QGroupBox("🔧 其他设置")
        group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                color: black;
                background-color: white;
                border: 1px solid #ccc;
                border-radius: 6px;
                margin-top: 8px;
                padding-top: 8px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
                color: black;
            }
        """)
        layout = QVBoxLayout(group)
        layout.setSpacing(8)
     
        
        # 底部开关
        bottom_switches = [
            ("期望岗位", "positionsw", "position"), ("工作地点", "locationsw", "location"), 
            ("标签介绍", "tagssw", "tags"), ("学校工作经历", "experiencesw", "experience")
        ]
        
        self.other_switches = {}
        self.other_inputs = {}
        for text, switch_key, content_key in bottom_switches:
            switch_layout = QHBoxLayout()
            switch_layout.setSpacing(5)
            
            label = QLabel(text)
            label.setStyleSheet("color: black; font-size: 11px;")
            label.setFixedWidth(70)
            
            switch = ToggleSwitch(text, self.config_data.get(switch_key, False))
            self.other_switches[text] = switch
            
            input_box = QLineEdit()
            input_box.setText(self.config_data.get(content_key, ""))
            input_box.setFixedWidth(200)
            input_box.setStyleSheet(self.input_style)
            input_box.setPlaceholderText(f"请输入{text}相关信息")
            self.other_inputs[text] = input_box
            
            help_label = QLabel("❓")
            help_label.setStyleSheet("color: #666; font-size: 12px;")
            help_label.setFixedSize(16, 16)
            
            switch_layout.addWidget(label)
            switch_layout.addWidget(switch)
            switch_layout.addWidget(input_box)
            switch_layout.addWidget(help_label)
            switch_layout.addStretch()  # 添加弹性空间，使控件左对齐
            
            layout.addLayout(switch_layout)
        parent_layout.addWidget(group)

    def update_greeting_records(self):
        """更新招呼记录到配置数据"""
        self.config_data["tableData"] = [
            {"name": int(data[0]), "address": str(data[1])}
            for data in self.table_model._data
        ]
    
    def create_right_panel(self, parent_layout):
        """创建右侧面板"""
        right_widget = QWidget()
        right_widget.setStyleSheet("""
            QWidget {
                background-color: #f8f9fa;
                border: 1px solid #e9ecef;
                border-radius: 8px;
            }
        """)
        right_layout = QVBoxLayout(right_widget)
        right_layout.setContentsMargins(16, 16, 16, 16)
        right_layout.setSpacing(16)
        
        # 功能开关区域 - 卡片样式
        function_card = QWidget()
        function_card.setStyleSheet("""
            QWidget {
                background-color: white;
                border: 1px solid #e9ecef;
                border-radius: 8px;
            }
        """)
        function_card_layout = QVBoxLayout(function_card)
        function_card_layout.setContentsMargins(12, 12, 12, 12)
        function_card_layout.setSpacing(8)
        
        # 功能开关标题
        function_title = QLabel("功能设置")
        function_title.setStyleSheet("color: black; font-size: 14px; font-weight: bold; margin-bottom: 8px;")
        function_card_layout.addWidget(function_title)
        
        right_switches_layout = QGridLayout()
        right_switches_layout.setSpacing(8)
        right_switches_layout.setVerticalSpacing(8)
        
        function_switches = [
            ("打招呼", True), ("优先执行", True), ("交换微信手机", False),
            ("回复新消息", True), ("过滤同事已聊", False), ("推荐牛人", True)
        ]
        
        for i, (text, checked) in enumerate(function_switches):
            switch = ToggleSwitch(text, checked)
            label = QLabel(text)
            label.setStyleSheet("color: black; font-size: 12px;")
            
            row = i // 2
            col = (i % 2) * 2
            right_switches_layout.addWidget(label, row, col)
            right_switches_layout.addWidget(switch, row, col + 1)
        
        function_card_layout.addLayout(right_switches_layout)
        right_layout.addWidget(function_card)
        
        # 筛选条件区域 - 卡片样式
        filter_card = QWidget()
        filter_card.setStyleSheet("""
            QWidget {
                background-color: white;
                border: 1px solid #e9ecef;
                border-radius: 8px;
            }
        """)
        filter_card_layout = QVBoxLayout(filter_card)
        filter_card_layout.setContentsMargins(12, 12, 12, 12)
        filter_card_layout.setSpacing(12)
        
        # 筛选条件标题
        filter_title = QLabel("筛选条件")
        filter_title.setStyleSheet("color: black; font-size: 14px; font-weight: bold; margin-bottom: 8px;")
        filter_card_layout.addWidget(filter_title)
        
        # 年龄范围
        age_layout = QHBoxLayout()
        age_layout.setSpacing(8)
        
        age_label = QLabel("年龄限制")
        age_label.setStyleSheet("color: black; font-size: 12px;")
        age_layout.addWidget(age_label)
        
        age_input1 = QLineEdit("10")
        age_input1.setFixedWidth(50)
        age_input1.setStyleSheet(self.input_style)
        age_layout.addWidget(age_input1)
        
        age_to_label = QLabel("到")
        age_to_label.setStyleSheet("color: black; font-size: 12px;")
        age_layout.addWidget(age_to_label)
        
        age_input2 = QLineEdit("99")
        age_input2.setFixedWidth(50)
        age_input2.setStyleSheet(self.input_style)
        age_layout.addWidget(age_input2)
        
        age_unit_label = QLabel("岁")
        age_unit_label.setStyleSheet("color: black; font-size: 12px;")
        age_layout.addWidget(age_unit_label)
        
        age_layout.addStretch()
        filter_card_layout.addLayout(age_layout)
        
        # 薪资范围
        salary_layout = QHBoxLayout()
        salary_layout.setSpacing(8)
        
        salary_label = QLabel("薪资范围")
        salary_label.setStyleSheet("color: black; font-size: 12px;")
        salary_layout.addWidget(salary_label)
        
        salary_input1 = QLineEdit("2")
        salary_input1.setFixedWidth(50)
        salary_input1.setStyleSheet(self.input_style)
        salary_layout.addWidget(salary_input1)
        
        salary_to_label = QLabel("千 --")
        salary_to_label.setStyleSheet("color: black; font-size: 12px;")
        salary_layout.addWidget(salary_to_label)
        
        salary_input2 = QLineEdit("25")
        salary_input2.setFixedWidth(50)
        salary_input2.setStyleSheet(self.input_style)
        salary_layout.addWidget(salary_input2)
        
        salary_unit_label = QLabel("万")
        salary_unit_label.setStyleSheet("color: black; font-size: 12px;")
        salary_layout.addWidget(salary_unit_label)
        salary_layout.addStretch()
        filter_card_layout.addLayout(salary_layout)
        
        # 活跃度选择
        activity_layout = QHBoxLayout()
        activity_layout.setSpacing(8)
        
        activity_label = QLabel("活跃度")
        activity_label.setStyleSheet("color: black; font-size: 12px;")
        activity_layout.addWidget(activity_label)
        
        activity_options = ["今日活跃", "3天内活跃", "7天内活跃", "30天内活跃"]
        for option in activity_options:
            cb = QCheckBox(option)
            if option == "今日活跃":
                cb.setChecked(True)
            cb.setStyleSheet("""
                QCheckBox {
                    color: black;
                    font-size: 11px;
                    spacing: 5px;
                }
                QCheckBox::indicator {
                    width: 16px;
                    height: 16px;
                }
                QCheckBox::indicator:unchecked {
                    border: 1px solid #ccc;
                    background-color: white;
                    border-radius: 3px;
                }
                QCheckBox::indicator:checked {
                    border: 1px solid #007bff;
                    background-color: #007bff;
                    border-radius: 3px;
                }
            """)
            activity_layout.addWidget(cb)
        
        filter_card_layout.addLayout(activity_layout)
        
        # 学历选择
        education_layout = QHBoxLayout()
        education_layout.setSpacing(8)
        
        education_label = QLabel("学历不限")
        education_label.setStyleSheet("color: black; font-size: 12px;")
        education_layout.addWidget(education_label)
        
        education_options = ["初中及以下", "中专/中技", "高中", "大专", "本科", "硕士", "博士"]
        for i, option in enumerate(education_options):
            cb = QCheckBox(option)
            if option in ["大专", "本科"]:
                cb.setChecked(True)
            cb.setStyleSheet("""
                QCheckBox {
                    color: black;
                    font-size: 11px;
                    spacing: 5px;
                }
                QCheckBox::indicator {
                    width: 16px;
                    height: 16px;
                }
                QCheckBox::indicator:unchecked {
                    border: 1px solid #ccc;
                    background-color: white;
                    border-radius: 3px;
                }
                QCheckBox::indicator:checked {
                    border: 1px solid #007bff;
                    background-color: #007bff;
                    border-radius: 3px;
                }
            """)
            education_layout.addWidget(cb)
        
        filter_card_layout.addLayout(education_layout)
        right_layout.addWidget(filter_card)
        
        # 意向选择区域 - 卡片样式
        intention_card = QWidget()
        intention_card.setStyleSheet("""
            QWidget {
                background-color: white;
                border: 1px solid #e9ecef;
                border-radius: 8px;
            }
        """)
        intention_card_layout = QVBoxLayout(intention_card)
        intention_card_layout.setContentsMargins(12, 12, 12, 12)
        intention_card_layout.setSpacing(8)
        
        # 意向选择标题
        intention_title = QLabel("求职意向")
        intention_title.setStyleSheet("color: black; font-size: 14px; font-weight: bold; margin-bottom: 8px;")
        intention_card_layout.addWidget(intention_title)
        
        intention_layout = QHBoxLayout()
        intention_layout.setSpacing(8)
        
        intention_label = QLabel("意向不限")
        intention_label.setStyleSheet("color: black; font-size: 12px;")
        intention_layout.addWidget(intention_label)
        
        intention_options = ["在职-找工作", "离职-找工作", "在职-不找工作", "在职-看机会"]
        for option in intention_options:
            cb = QCheckBox(option)
            if option == "离职-找工作":
                cb.setChecked(True)
            cb.setStyleSheet("""
                QCheckBox {
                    color: black;
                    font-size: 11px;
                    spacing: 5px;
                }
                QCheckBox::indicator {
                    width: 16px;
                    height: 16px;
                }
                QCheckBox::indicator:unchecked {
                    border: 1px solid #ccc;
                    background-color: white;
                    border-radius: 3px;
                }
                QCheckBox::indicator:checked {
                    border: 1px solid #007bff;
                    background-color: #007bff;
                    border-radius: 3px;
                }
            """)
            intention_layout.addWidget(cb)
        
        intention_card_layout.addLayout(intention_layout)
        right_layout.addWidget(intention_card)
        
        # 学校设置区域 - 卡片样式
        school_card = QWidget()
        school_card.setStyleSheet("""
            QWidget {
                background-color: white;
                border: 1px solid #e9ecef;
                border-radius: 8px;
            }
        """)
        school_card_layout = QVBoxLayout(school_card)
        school_card_layout.setContentsMargins(12, 12, 12, 12)
        school_card_layout.setSpacing(8)
        
        # 学校设置标题
        school_title = QLabel("学校设置")
        school_title.setStyleSheet("color: black; font-size: 14px; font-weight: bold; margin-bottom: 8px;")
        school_card_layout.addWidget(school_title)
        
        degree_layout = QHBoxLayout()
        degree_layout.setSpacing(8)
        
        degree_label = QLabel("学历不限")
        degree_label.setStyleSheet("color: black; font-size: 12px;")
        degree_layout.addWidget(degree_label)
        
        degree_input1 = QLineEdit("985")
        degree_input1.setFixedWidth(60)
        degree_input1.setStyleSheet(self.input_style)
        degree_layout.addWidget(degree_input1)
        
        degree_211_label = QLabel("211")
        degree_211_label.setStyleSheet("color: black; font-size: 12px;")
        degree_layout.addWidget(degree_211_label)
        
        degree_input2 = QLineEdit("211")
        degree_input2.setFixedWidth(60)
        degree_input2.setStyleSheet(self.input_style)
        degree_layout.addWidget(degree_input2)
        
        degree_layout.addStretch()
        school_card_layout.addLayout(degree_layout)
        right_layout.addWidget(school_card)
        
        # 底部开关区域 - 卡片样式
        bottom_card = QWidget()
        bottom_card.setStyleSheet("""
            QWidget {
                background-color: white;
                border: 1px solid #e9ecef;
                border-radius: 8px;
            }
        """)
        bottom_card_layout = QVBoxLayout(bottom_card)
        bottom_card_layout.setContentsMargins(12, 12, 12, 12)
        bottom_card_layout.setSpacing(8)
        
        # 底部开关标题
        bottom_title = QLabel("其他设置")
        bottom_title.setStyleSheet("color: black; font-size: 14px; font-weight: bold; margin-bottom: 8px;")
        bottom_card_layout.addWidget(bottom_title)
        
        bottom_switches = [
            ("期望岗位", False),
            ("工作地点", False),
            ("标签介绍", False),
            ("学校工作经历", False)
        ]
        
        for text, checked in bottom_switches:
            switch_layout = QHBoxLayout()
            switch_layout.setSpacing(8)
            
            switch = ToggleSwitch(text, checked)
            label = QLabel(text)
            label.setStyleSheet("color: black; font-size: 12px;")
            
            switch_layout.addWidget(label)
            switch_layout.addWidget(switch)
            
            help_label = QLabel("❓")
            help_label.setStyleSheet("""
                QLabel {
                    color: #6c757d;
                    font-size: 14px;
                    padding: 2px;
                }
                QLabel:hover {
                    color: #007bff;
                }
            """)
            help_label.setFixedSize(20, 20)
            switch_layout.addWidget(help_label)
            switch_layout.addStretch()
            
            bottom_card_layout.addLayout(switch_layout)
        
        right_layout.addWidget(bottom_card)
        
        right_layout.addStretch()
        parent_layout.addWidget(right_widget)